import {api, baseAjax} from '@/api/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import {statusCode} from '@/utils/index'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  //登录
  login({ commit }, userInfo) {
    const { email, password, supplierType } = userInfo;
    return new Promise((resolve)=>{
      baseAjax(api.login, {email: email.trim(), password, supplierType}, function(res){
        if(res.code === statusCode.success){
          commit('SET_TOKEN', res.code+'');
          setToken(res.code+'');
        }
        resolve(res)
      })
    })
  },

  //获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve) => {
      baseAjax(api.getInfo, "", function(res){
        if(res.code === 20000){
          const { name, photo_path:avatar } = res
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
        }
        resolve(res)
      })
    })
  },

  //退出
  logout({ commit, state }) {
    return new Promise((resolve) => {
      removeToken()
      resetRouter()
      commit('RESET_STATE')
      state.token = ''
      resolve()
    })
  },

  //清空token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
